<script setup lang="ts">
import { getChatHistoryList } from '@/api/chatHistoryController.ts'
import { onMounted, ref } from 'vue'
import AiChatComponent from '@/components/ai/AiChatComponent.vue'

interface DataItem {
  userMessage: string
  aiMessage: string
  chatId: string
}
const data = ref<DataItem[]>([])
const open = ref<boolean>(false)
let showDetailChatId = ref<string>('')

const fetChatHistory = async () => {
  const chatHistoryList = await getChatHistoryList()

  // 定义接口返回类型
  type ApiResponse = {
    code: number
    data: { [chatId: string]: ChatHistory[] } // chatId 对应的聊天记录
    message: string
  }
  type ChatHistory = {
    id: string
    chatId: string
    type: number
    message: string
    chatTime?: string
  }

  // 断言类型
  const rawData = chatHistoryList.data as ApiResponse

  // 真正的聊天数据在 rawData.data 里！
  const chatData = rawData.data

  // 遍历真正的 chatId（仅 chatData 的键）
  for (const chatId in chatData) {
    const chatRecords = chatData[chatId]

    // 保证至少 2 条记录
    if (chatRecords && chatRecords.length >= 2) {
      const userMsgRecord = chatRecords[0]
      const aiMsgRecord = chatRecords[1]
      const newItem: DataItem = {
        userMessage: userMsgRecord.message,
        aiMessage: aiMsgRecord.message,
        chatId: chatId,
      }
      data.value.push(newItem)
    }
  }
}

const showDetail = (chatId: string) => {
  showDetailChatId.value = chatId
  open.value = true
}

onMounted(() => {
  fetChatHistory()
})
</script>

<template>
  <div class="chat-history-page">
    <a-list item-layout="horizontal" :data-source="data">
      <template #renderItem="{ item }">
        <a-list-item @click="showDetail(item.chatId)">
          <a-list-item-meta :description="item.aiMessage">
            <template #title>
              <a href="#">{{ item.userMessage }}</a>
            </template>
            <template #avatar>
              <a-avatar style="background-color: white"> 🤖 </a-avatar>
            </template>
          </a-list-item-meta>
        </a-list-item>
      </template>
    </a-list>
    <a-drawer
      v-model:open="open"
      class="custom-class"
      root-class-name="root-class-name"
      width="520"
      :root-style="{ color: 'blue' }"
      style="color: black"
      title="农业小组手"
      placement="right"
    >
      <div>
        <AiChatComponent :chatId="showDetailChatId" />
      </div>
    </a-drawer>
  </div>
</template>

<style scoped></style>
